﻿using Infrastructure.Image;
using Infrastructure.Json;
using MyData;
using MyData.Dto;
using MyData.Models;
using MyWeb.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyWeb.Controllers
{
    public class HAController : BaseController
    {
        private static string imgPath = @"/Attach/Record/";
        // GET: HA
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult ApiIndex()
        {
            string command = Request.Headers["Command"].ToString();

            JsonResult result = null;
            switch (command)
            {
                case "record":
                    result = SaveAccessRecord();
                    break;
                case "gettask":
                    result = GetTaskList();
                    break;
                case "getface":
                    result = GetUserInfo();
                    break;
                case "report":
                    result = Report();
                    break;
                default: break;
            }
            return result;

        }
        /// <summary>
        /// 上传刷脸记录
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        JsonResult SaveAccessRecord()
        {
            ResultBaseDto result = new ResultBaseDto();
            try
            {
                AccessRecord accessRecord = new AccessRecord();
                Stream stream = Request.InputStream;
                string json = string.Empty;
                string responseJson = string.Empty;
                if (stream.Length != 0)
                {
                    StreamReader streamReader = new StreamReader(stream);
                    json = streamReader.ReadToEnd();
                    AccessInput access = (AccessInput)json.ToJson();
                    accessRecord.UserId = access.userID;
                    string machineCode = access.machineCode;
                    float similar = access.similar;
                    accessRecord.Similar = similar;
                    if (!string.IsNullOrEmpty(access.photo))
                    {
                        Bitmap bitmap = ImageHelper.ConvertStringToBitmap("data:image/jpeg;base64," + access.photo);
                        string fullPath = AppDomain.CurrentDomain.BaseDirectory + imgPath;
                        if (!Directory.Exists(fullPath))
                        {
                            Directory.CreateDirectory(fullPath);
                        }
                        string fileName = Guid.NewGuid().ToString() + ".jpg";
                        bitmap.Save(fullPath + fileName);
                        accessRecord.PicPath = imgPath + fileName;
                    }
                    AccessRecordApp.SaveAccessRecordRM(accessRecord, machineCode);

                }
            }
            catch (Exception ex)
            {
                result.errorcode = -1;
                result.msg = ex.Message;


            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        ///获取设备任务列表
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        JsonResult GetTaskList()
        {
            GetTaskListResultDto result = new GetTaskListResultDto();

            try
            {
                Stream stream = Request.InputStream;
                string json = string.Empty;
                string responseJson = string.Empty;
                if (stream.Length != 0)
                {
                    StreamReader streamReader = new StreamReader(stream);
                    json = streamReader.ReadToEnd();
                    TaskInput task = (TaskInput)json.ToJson();

                    Mobile mobile = new Mobile();
                    mobile.ImeiNum = mobile.Name = task.machineCode;
                    mobile.Ip = task.ip;
                    mobile.CameraIp = task.authCode;
                    mobile.CameraName = task.mac;
                    mobile.Port = task.statCode;
                    mobile.CameraPass = task.versionCode.ToJson();

                    Guid deviceId = mobileApp.SaveMobile(mobile);
                    var syncs = SynsRlApp.GetSynsUsers(deviceId);
                    List<TaskDto> list = new List<TaskDto>();
                    foreach (var dto in syncs)
                    {
                        int operate = dto.OperateType == (int)EnumOperateType.删除 ? 102 : 101;
                        list.Add(new TaskDto()
                        {
                            taskcmd = operate,
                            taskid = dto.UserId
                        });
                    }
                    result.tasks = list;
                }
            }
            catch (Exception ex)
            {
                result.errorcode = -1;
                result.msg = ex.Message;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        JsonResult GetUserInfo()
        {
            GetFaceResultDto result = new GetFaceResultDto();
            try
            {

                Stream stream = Request.InputStream;
                string json = string.Empty;
                string responseJson = string.Empty;
                if (stream.Length != 0)
                {
                    StreamReader streamReader = new StreamReader(stream);
                    json = streamReader.ReadToEnd();
                    UserInfoInput userInfo = (UserInfoInput)json.ToJson();
                 
                    Guid synsId = userInfo.faceid;
                    var syns = SynsRlApp.GetSynsRlById(synsId);
                    UserInfoDto user = userInfoApp.GetUserInfo(syns.UserId);

                    result.faceBase64 = ImageHelper.GetBase64FromImage1((Bitmap)Image.FromFile(AppDomain.CurrentDomain.BaseDirectory+"/"+user.HeadUrl));
                    result.idcNumber = user.CardNum;
                    result.name = user.NickName;
                    result.userid = user.Id;
                }
            }
            catch (Exception ex)
            {
                result.errorcode = -1;
                result.msg = ex.Message;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        JsonResult Report()
        {
            ResultBaseDto result = new ResultBaseDto();
            try
            {
                Stream stream = Request.InputStream;
                string json = string.Empty;
                string responseJson = string.Empty;
                if (stream.Length != 0)
                {
                    StreamReader streamReader = new StreamReader(stream);
                    json = streamReader.ReadToEnd();
                    ReportInput report = (ReportInput)json.ToJson();
                    Guid id = report.taskid;
                    SynsRlApp.DeleteSynsById(id);
                }
            }
            catch (Exception ex)
            {
                result.errorcode = -1;
                result.msg = ex.Message;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}